package com.kkm.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
    jdbc工具类
 */
public class JdbcUtils_Druid {
    //创建连接池
private  static DataSource dataSource;
    static{
        try {
            Properties pop=new Properties();
            //从src下加载配置文件
            InputStream in=JdbcUtils_Druid.class.getClassLoader().getResourceAsStream("Druid.properties");
            //配置文件数据加载进集合
            pop.load(in);
            //sun接口Datasource==阿里巴巴连接池实现对象
            dataSource= DruidDataSourceFactory.createDataSource(pop);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 获取数据源：DataSource
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 获取链接
     */
    public static Connection getConnection() throws SQLException {
        //获取链接
        return dataSource.getConnection();
    }

    /**
     *
     * 释放资源
     */
    public static void release(AutoCloseable...all){
        for(AutoCloseable ac : all){
            if(ac!=null) {
                try {
                    ac.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
